package main

import (
	"io/ioutil"
	"os"
	"fmt"
	"bufio"
)

func check(e error)  {
	if e!=nil{
		panic(e)
	}
}

func main()  {
	destname:="/home/xiaonu/Desktop/dat1.txt"
	d1:=[]byte("hello\ngo\n")
	err:=ioutil.WriteFile(destname,d1,os.ModePerm)
	check(err)

	//更细致的写入
	f,err:=os.Create(destname)
	check(err)
	defer f.Close()//打开文件后应习惯用defer关闭文件
	//现在可以写入你想写的字节切片
	d2:=[]byte{115,111,109,101,10}
	n2,err:=f.Write(d2)
	check(err)
	fmt.Printf("write %d bytes\n",n2)

	n3,err:=f.WriteString("writes\n")
	fmt.Printf("write %d bytes\n",n3)

	//调用sync来将缓冲区的信息写入磁盘
	f.Sync()
	//bufio提供了带缓冲的写入器
	w:=bufio.NewWriter(f)
	n4,err:=w.WriteString("buffered\n")
	fmt.Printf("write %d bytes\n",n4)
	//使用flush来确保所有缓存的操作已写入底层写入器
	w.Flush()

}
